/**
 * 
 */
package com.wkinney.util;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Collection;
import java.util.Vector;

/**
 * @author http://snippets.dzone.com/posts/show/1875
 * 
 */
public class FileUtil {

    /**
     * 
     * @param directory
     * @param filter
     * @param recurse
     * @return
     */
    public static File[] listFilesAsArray(File directory, FilenameFilter filter, boolean recurse, boolean onlyFiles) {
        final Collection<File> files = FileUtil.listFiles(directory, filter, recurse, onlyFiles);

        final File[] arr = new File[files.size()];
        return files.toArray(arr);
    }

    /**
     * 
     * @param directory
     * @param filter
     * @param recurse
     * @return
     */
    public static Collection<File> listFiles(File directory, FilenameFilter filter, boolean recurse, boolean onlyFiles) {
        // List of files / directories
        final Vector<File> files = new Vector<File>();

        // Get files / directories in the directory
        final File[] entries = directory.listFiles();

        // Go over entries
        for (final File entry : entries) {

            
            // If there is no filter or the filter accepts the
            // file / directory, and if we only want files and the file is a file, add it to the list
            if ((filter == null || filter.accept(directory, entry.getName())) 
                    && (!onlyFiles || (onlyFiles && entry.isFile()))) {
                files.add(entry);
            }

            // If the file is a directory and the recurse flag
            // is set, recurse into the directory
            if (recurse && entry.isDirectory()) {
                files.addAll(FileUtil.listFiles(entry, filter, recurse, onlyFiles));
            }
        }

        // Return collection of files
        return files;
    }

}
